package org.apdplat.realtimelog.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apdplat.realtimelog.common.BaseResponse;
import org.apdplat.realtimelog.common.Constant;
import org.apdplat.realtimelog.manager.RedisManager;
import org.apdplat.realtimelog.utils.CookieUtils;
import org.apdplat.realtimelog.utils.TokenUtils;
import org.apdplat.realtimelog.web.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private RedisManager redisManager;

	@RequestMapping("/login")
	public BaseResponse<String> login(@RequestBody LoginUser user, HttpServletRequest request, HttpServletResponse response) {
		String token = TokenUtils.generateToken();
		CookieUtils.setCookie(response, Constant.LOGIN_TOKEN_KEY, token);
		redisManager.set(token, user);
		return BaseResponse.success();
	}
	
	@RequestMapping("/loginOut")
	public void loginOut(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String token = TokenUtils.getLoginToken(request);
		CookieUtils.removeCookie(request, response, token);
		redisManager.delete(token);
		response.sendRedirect(request.getAttribute("basePath")+"/login");
	}

}
